# -*- coding:utf-8 -*-
from datetime import datetime

import torndb

import setting
from util.wechatpy.custom import WeChatCustom

class Gift(object):

    """
    赠送  24小时未领取的赠送商品，返还给赠送人

    """

    def __init__(self):

        self.db = torndb.Connection(
            host=setting.mysql_host,
            database=setting.mysql_database,
            user=setting.mysql_user,
            password=setting.mysql_password,
            time_zone="+8:00",
            charset='utf8mb4',
            max_idle_time=900,
            connect_timeout=900
        )
        self.custom = WeChatCustom()
        self.url = setting.mobile_url + "/weshop/reserve"

    def _get_unreceive_gifts(self):
        gifts = self.db.query("select id, user_id, status from t_gift where return_status=0 and TIMESTAMPDIFF(SECOND, create_date, now()) > 86400")
        for gift in gifts:
            yield gift

    def _get_gift_product_receive(self, gift_id):
        product_receives = self.db.query("select id, product_id from r_gift_product_receive where gift_id = %(gift_id)s and status=0", gift_id=gift_id)
        for pr in product_receives:
            yield pr

    def _get_product_titles(self, pids=[]):
        products = self.db.query("select title from t_product where id in %(pids)s", pids=tuple(pids))
        titles = map(lambda x: x["title"], products)
        return u",".join(titles)

    def _get_wechat(self, user_id):
        return self.db.get("select openid from t_wechat where user_id = %(user_id)s", user_id=user_id)

    def _update_gift_product_receive(self, pr_id):
        self.db.execute("update r_gift_product_receive set status=2 where id=%(pr_id)s", pr_id=pr_id)

    def _update_gift(self, gift_id, status):

        # 如果是24小都未分享的，将状态置为已失效4
        if status == 2:
            self.db.execute("update t_gift set status = 4, return_status = 1 where id=%(gift_id)s", gift_id=gift_id)
        else:
            self.db.execute("update t_gift set return_status = 1 where id=%(gift_id)s", gift_id=gift_id)

    def runner(self):
        gifts = self._get_unreceive_gifts()
        for gift in gifts:
            print u"gift.id:{} {}".format(gift.id, datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

            # check git status=1 的直接更新处理flag
            if gift.status == 1:
                print u"gift.id:{} {} status 1".format(gift.id, datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                self._update_gift(gift.id, gift.status)
                continue

            pids = []
            product_receives = self._get_gift_product_receive(gift.id)
            for pr in product_receives:
                print u"pr.id:{} {}".format(pr.id, datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                self._update_gift_product_receive(pr.id)
                if pr.product_id not in pids:
                    print u"{} in pids {}".format(pr.product_id, datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                    pids.append(pr.product_id)

            self._update_gift(gift.id, gift.status)

            if pids:
                print u"send notice {}".format(pr.product_id, datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

                # 发送客服通知
                titles = self._get_product_titles(pids)
                wechat = self._get_wechat(gift.user_id)
                content = u"24小时前赠送的商品{}未被领取, 已退回您的账户~\n<a href=\"{}\">查看我的存货库</a>".format(titles, self.url)

                res = self.custom.send(wechat.openid, content)
                print res

if __name__ == '__main__':
    print "run start : {}".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    gift = Gift()
    gift.runner()
    gift.db.close()
    print "run end : {}".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))